package ru.bytedog.oiot.counter.bot.bean.oiot;

import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import ru.bytedog.oiot.counter.bot.service.adapter.LocalDateTimeAdapter;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Stream;

/**
 * Успешный ответ от сервиса OIOT.RU c показателями счетчиков
 */
@Data
@NoArgsConstructor
public class OiotSuccessResponse implements IOiotResponse {

    private Map<String, OiotResultData> result;

    @Override
    public String getBotMessage() {
        StringBuilder stringBuilder = new StringBuilder();
        Optional.ofNullable(result)
                .map(Map::values)
                .orElse(Collections.emptyList())
                .forEach(counter -> {
                    Optional<OiotCounterData> lastCounterData = Optional.ofNullable(counter)
                            .map(OiotResultData::getData)
                            .map(List::stream)
                            .flatMap(Stream::findFirst);
                    if (lastCounterData.isEmpty()) {
                        stringBuilder.append("Показатели не найдены\n");
                        return;
                    }
                    stringBuilder.append("Показатели на ").append(lastCounterData
                                    .map(OiotCounterData::getDate)
                                    .map(date -> date.format(LocalDateTimeAdapter.SERIALIZE))
                                    .orElse(StringUtils.EMPTY))
                            .append("\n");
                    stringBuilder.append(counter.getTitle()).append("\n");
                    if (StringUtils.isNotBlank(counter.getCounterName1())) {
                        stringBuilder.append(counter.getCounterName1()).append(": ").append(lastCounterData
                                        .map(oiotCounterData -> oiotCounterData.getCounter1() + " " + counter.getMeasure1())
                                        .orElse("-"))
                                .append("\n");
                    }
                    if (StringUtils.isNotBlank(counter.getCounterName2())) {
                        stringBuilder.append(counter.getCounterName2()).append(": ").append(lastCounterData
                                        .map(oiotCounterData -> oiotCounterData.getCounter2() + " " + counter.getMeasure2())
                                        .orElse("-"))
                                .append("\n");
                    }
                });
        return stringBuilder.toString();
    }


}
